package com.chianghao.rock.system.service.role;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chianghao.core.frame.service.BaseService;
import com.chianghao.core.mybatis.plugins.Paging;
import com.chianghao.core.mybatis.sql.SqlWrapper;
import com.chianghao.core.mybatis.sql.db_enum.SqlOperators;
import com.chianghao.rock.system.dao.role.RoleMapper;
import com.chianghao.rock.system.dao.user_role.UserRoleMapper;
import com.chianghao.rock.system.entity.Role;
import com.chianghao.rock.system.entity.UserRole;

@Service
public class RoleService extends BaseService<RoleMapper, Role> {

	
	@Autowired
	UserRoleMapper userRoleMapper;
	
	public List<Role> query(String name) {
		SqlWrapper sqlWrapper  = null;
		if(StringUtils.isNotEmpty(name)) {
			sqlWrapper = new SqlWrapper().addCondition(Role::getName,SqlOperators.behind_like,name);
		}
		return this.mapper.queryList(sqlWrapper);
	}

	public List<Role> queryPage(String name, Paging paging) {
		SqlWrapper sqlWrapper  = null;
		if(StringUtils.isNotEmpty(name)) {
			sqlWrapper = new SqlWrapper().addCondition(Role::getName,SqlOperators.behind_like,name);
		}
		return this.mapper.queryPageList(paging, sqlWrapper);
	}

	
	
	public List<Role> queryUserRole(Long userId) {
		UserRole where  = new UserRole();
		where.setUserId(userId);
		
		List<UserRole> list  = this.userRoleMapper.queryListByEntity(where, null);
		List<Long> ids = list.stream().map(item->item.getRoleId()).collect(Collectors.toList());
	
		if(ids!=null&&ids.size()>0) {
			SqlWrapper wrapper  = new SqlWrapper();
			wrapper.addInCondition(Role::getId, ids);
			return this.mapper.queryList(wrapper);
		}
		
		return new ArrayList<Role>();
	}

	
	public void doSetUserRole(Long userId, List<Long> roles) {
		if(roles==null||roles.size()==0) {
			return;
		}
		
		UserRole where  = new UserRole();
		where.setUserId(userId);
		this.userRoleMapper.deleteByEntity(where);
		
		List<UserRole> list = new ArrayList<UserRole>();
		for(Long role:roles) {
			UserRole userRole = new UserRole();
			userRole.setRoleId(role);
			userRole.setUserId(userId);
			list.add(userRole);
		}
        
		this.userRoleMapper.batchInsert(list);
	}

	
	



}